<?php

namespace common\modules\user\models;

use common\components\ActiveRecord;
use common\models\Setting;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\IdentityInterface;

/**
 * 管理员模型
 *
 * @property int    id
 * @property string auth_key
 * @property string access_token
 * @property string username
 * @property string email
 * @property string password
 * @package common\modules\user\models
 */
class Admin extends ActiveRecord implements IdentityInterface
{

    /**
     * @var array 超级管理员
     */
    static $rootUser = [
        'id'           => 0,
        'username'     => 'root',
        'email'        => 'dev@tourze.com',
        'password'     => '',
        'auth_key'     => '',
        'access_token' => '',
    ];

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%rbac_admin}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['username', 'email'], 'required'],
            [['username', 'email'], 'unique'],
            ['password', 'required', 'on' => 'create'],
            ['password', 'safe'],
            ['access_token', 'default', 'value' => null],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'username' => Yii::t('backend', 'Username'),
            'email'    => Yii::t('backend', 'Email'),
            'password' => Yii::t('backend', 'Password'),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert))
        {
            if ($this->isNewRecord)
            {
                $this->auth_key = $this->generateAuthKey();
                $this->password = $this->hashPassword($this->password);
            }
            else
            {
                $this->password = $this->password != '' ? $this->hashPassword($this->password) : $this->oldAttributes['password'];
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        $result = null;
        try
        {
            $result = $id == self::$rootUser['id']
                ? static::createRootUser()
                : static::findOne($id);
        }
        catch (InvalidConfigException $e)
        {
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public static function findByUsername($username)
    {
        if ($username === self::$rootUser['username'])
        {
            return static::createRootUser();
        }
        return static::findOne(['username' => $username]);
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function validatePassword($password)
    {
        return $this->password === $this->hashPassword($password);
    }

    private function hashPassword($password)
    {
        return sha1($password . $this->getAuthKey() . Setting::get('password_salt'));
    }

    private function generateAuthKey()
    {
        return Yii::$app->security->generateRandomString();
    }

    public static function createRootUser()
    {
        return new static(array_merge(self::$rootUser, [
            'password' => Setting::get('root_password'),
            'auth_key' => Setting::get('root_auth_key'),
        ]));
    }

    public function isRoot()
    {
        return $this->id === self::$rootUser['id'];
    }
}
